package com.kexio.auth.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring上下文工具类
 * 用于在静态方法中获取Spring Bean
 * 
 * @author Kexio Team
 * @since 2.0.0
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
    
    /**
     * 获取Spring Bean
     * 
     * @param clazz Bean类型
     * @return Bean实例，如果不存在则返回null
     */
    public static <T> T getBean(Class<T> clazz) {
        try {
            return applicationContext != null ? applicationContext.getBean(clazz) : null;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取Spring Bean
     * 
     * @param name Bean名称
     * @param clazz Bean类型
     * @return Bean实例，如果不存在则返回null
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        try {
            return applicationContext != null ? applicationContext.getBean(name, clazz) : null;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 检查Spring上下文是否已初始化
     */
    public static boolean isContextInitialized() {
        return applicationContext != null;
    }
}
